package cn.wuyi.common.rest;


import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import cn.wuyi.common.context.ContextHolder;
import cn.wuyi.common.context.ContextParameter;


public class RestTemplateExt extends RestTemplate{
	
	private static Logger logger = LoggerFactory.getLogger(RestTemplateExt.class);
	
	
	private Long appId;

	private String tenantId;
	
	public Long getAppId() {
		return appId;
	}

	public void setAppId(Long appId) {
		this.appId = appId;
	}

	public String getTenantId() {
		return tenantId;
	}

	public void setTenantId(String tenantId) {
		this.tenantId = tenantId;
	}

	
	/**
	 * @方法功能说明：清理从当前线程中获取的RestTemplateExtd对象的属性,使其恢复默认值,防止影响其他方法调用
	 * 原因：每次从当前线程获取RestTemplateExtd发送http请求结束后,并不需要清理当前线程的RestTemplateExtd对象,但需要清理该RestTemplateExtd对象的属性
	 * @作者        : administrator
	 * @创建时间    ：2018年7月16日 下午5:38:52
	 */
	public void clearAttr(){
		this.tenantId = null;
		this.appId = null;
	}
	
	public RestTemplateExt(){
		
	}
	
	public RestTemplateExt(ClientHttpRequestFactory requestFactory) {
		super(requestFactory);
	}

	/**
	 * @方法功能说明：根据传入的action url 获取baseUrl,如： /product/info?add
	 * @作者        : Administrator
	 * @创建时间    ：2016年10月12日 上午11:06:39 
	 * @param actionUrl
	 */
//	public void setBaseUri(String actionUrl){
//		UriTemplateHandler uriTemp =  this.getUriTemplateHandler();
//		String baseUrl = getBaseUrlByActionUrl(actionUrl);
////		uriTemp.setBaseUrl(baseUrl);
//		this.setUriTemplateHandler(uriTemp);
////	}
//	public boolean startHttp(String url){
//		if(StringUtils.isBlank(url)) return false;
//		String regex = "^([hH][tT]{2}[pP][sS]?://).*";
//		Pattern pattern = Pattern.compile(regex);
//		Matcher matcher = pattern.matcher(url);
//		return matcher.matches();
//	}
//
//	public String getBaseUrlByActionUrl(String actionUrl){
//		if(startHttp(actionUrl)){
//			return null;
//		}
//		return this.apiRouter.getBaseUrl(actionUrl);
//	}

	private String getTenantIdSuffix(){
		String tenantIdSuffix = "";
		logger.debug("### tenantId from this is {}",tenantId);
		if(tenantId == null){
			tenantId = ContextHolder. getContext().getTenantId();
			logger.debug("### tenantId from context is {}",tenantId);
		}
		if(tenantId != null){
			tenantIdSuffix = ContextParameter.TENANT_ID_PROPERTY + "=" + tenantId;
		}
		logger.debug("### Parameter tenantId from restTemplate value is {}!",tenantId);
		return tenantIdSuffix;
	}
	
	@Override
	protected <T> T doExecute(URI uri, HttpMethod method,RequestCallback requestCallback,ResponseExtractor<T> responseExtractor) throws RestClientException {
		if(uri != null){
			String termUri = uri.toString();
			String tenantIdSuffix = getTenantIdSuffix();
			String gatewayBaseUrl = System.getProperty("open.gateway.url", "");
			if(StringUtils.isNotBlank(gatewayBaseUrl)&&termUri.startsWith(gatewayBaseUrl)){
				tenantIdSuffix="";
			}
			if(StringUtils.isNotBlank(tenantIdSuffix)){
				if(!termUri.contains(ContextParameter.TENANT_ID_PROPERTY + "=")){
					if(termUri.contains("?")){
						termUri += "&" + tenantIdSuffix;
					}else{
						termUri += "?" + tenantIdSuffix;
					}
				}
				try {
					uri = new URI(termUri);
					logger.debug("### restTemplate After Requesting, URI => {}",uri);
				} catch (URISyntaxException e) {
					logger.error("Execute request with {} fail",termUri,e);
				}
			}
		}
		return super.doExecute(uri, method, requestCallback, responseExtractor);
	}
}
